package com.fnzn.entranceGuard.service.attendence.impl;

import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.fnzn.entranceGuard.entity.GuardQrInfo;
import com.fnzn.entranceGuard.mapper.attendance.AttendanceRecordMapper;
import com.fnzn.entranceGuard.service.IGuardQrInfoService;
import com.fnzn.entranceGuard.service.attendence.AttendanceRecordService;
import com.fnzn.entranceGuard.util.DateTools;
import com.github.pig.admin.model.attendance.AttendanceRecord;
import com.github.pig.common.constant.CommonConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author sxf
 * @since 2018-11-22
 */
@Service
public class AttendanceRecordServiceImpl extends ServiceImpl<AttendanceRecordMapper, AttendanceRecord> implements AttendanceRecordService {
    @Autowired
    private IGuardQrInfoService qrInfoService;
    @Autowired
    private AttendanceRecordMapper recordMapper;

    /**
     * 根据二维码内容考勤
     *
     * @param qrInfo
     */
    @Override
    public void attendanceByQr(String qrInfo) {
        GuardQrInfo info = qrInfoService.getByContent(qrInfo);
        //info = new GuardQrInfo();
        //info.setUserId("18369656586");
        if (info != null) {
            Date now = new Date();
            AttendanceRecord record = new AttendanceRecord();
            record.setDelFlag(CommonConstant.STATUS_NORMAL);
            record.setUserName(info.getUserId());
            record.setTime(now);
            //获取本日数据
            List<AttendanceRecord> records = recordMapper.getByUserForToday(info.getUserId());
            if(records !=null && !records.isEmpty() ){
                //有早勤卡  获取最后一条为晚勤卡
                if(AttendanceRecord.ATTEND_LATE.equals(records.get(records.size()-1).getRecordType())){
                    record = records.get(records.size()-1);
                    record.setTime(now);
                    recordMapper.updateById(record);
                    return ;
                }else{
                    //判断是否到达下班时间
                    if(!DateTools.isAttends(now,AttendanceRecord.ATTEND_LATE)){
                        //未到下班时间
                        return ;
                    }
                    record.setIsNormal( AttendanceRecord.IS_NORMAL);
                    record.setRecordType(AttendanceRecord.ATTEND_LATE);
                }
            }else{
                record.setIsNormal(judgeNormal(AttendanceRecord.ATTEND_EARLY,now));
                record.setRecordType(AttendanceRecord.ATTEND_EARLY);
            }
            recordMapper.insert(record);
        }
    }

    String judgeNormal(String recordType,Date now){
        if(DateTools.isAttends(now,recordType)){
           return  AttendanceRecord.IS_NORMAL;
        }else{
           return AttendanceRecord.IS_NORMAL_LATE;
        }
    }

}
